﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data;
using System.Web.UI.WebControls;

using Microsoft.Practices.Unity;

using Wuqi.Webdiyer;

using DreamBuilder.UI.UserControls;
using Web.SystemConfig.WorkFlow;
using Web.SystemLogin.Models;
using DreamBuilder.Common;
using Web.SystemConfig.Services;
using ePlanet.ArchiveMange.Services;
using System.Collections;
using Web.SystemConfig.SysCache;
using DreamBuilder.Core.Container;
using ePlanet.ArchiveMange.Enum;
using System.Text;
using System.EnterpriseServices;
using ePlanet.ArchiveMange.DataAccess;

/*
 * 时间：2013年4月4日 14:56:20
 * 备注：基类适用于上交、接收、办结界面
 */

namespace Web
{
    /// <summary>
    /// 档案流程业务基类
    /// </summary>
    public class ArchiveFlowPageBase : PageBase
    {
        [Dependency]
        public IArchiveMenuService IArchiveMenuService
        {
            get;
            set;
        }

        [Dependency]
        public ICodeTable ICodeTableService
        {
            get;
            set;
        }

        [Dependency]
        public IAuth_User IUserService
        { get; set; }


        public ArchiveFlowPageBase()
        {

        }

        private ArchiveBaseType _baseArchiveType;

        protected ArchiveBaseType BaseArchiveType
        {
            get
            {
                if ((int)_baseArchiveType == 0)
                {
                    _baseArchiveType = (ArchiveBaseType)IArchiveMenuService.GetArchiveBaseIDById((int)CurrentArchiveKind);
                }
                return _baseArchiveType;
            }
        }

        private ArchiveTableEnum _currArchiveKind;

        /// <summary>
        /// 当前页的档案类型-派生类需要指定
        /// </summary>
        protected ArchiveTableEnum CurrentArchiveKind
        {
            get
            {
                if (_currArchiveKind == 0)
                {
                    if (Request.QueryString["archiveType"] != null)
                    {
                        //int baseTypeId = IArchiveMenuService.GetArchiveBaseIDById(int.Parse(Request.QueryString["archiveType"]));
                        int baseTypeId = int.Parse(Request.QueryString["archiveType"]);
                        _currArchiveKind = (ArchiveTableEnum)baseTypeId;
                    }
                    else
                    {
                        throw new Exception("档案类型不能为空");
                    }
                }
                return _currArchiveKind;
            }
        }

        /// <summary>
        /// 提交流程操作名称-录入和审核都需要传入
        /// </summary>
        protected string PassFlowName;

        /// <summary>
        /// 退回流程操作名称-只审核需要传入
        /// </summary>
        protected string BackFlowName;

        /// <summary>
        /// 当前状态名称-比如 "录入中","移交中","初审中","接收中","审核中"
        /// </summary>
        protected string CurrentStatusName;

        /// <summary>
        /// 已移交
        /// </summary>
        protected EPGridView gvTransfered;

        /// <summary>
        /// 已移交分页
        /// </summary>
        protected AspNetPager pagerTransfered;

        /// <summary>
        /// 未移交
        /// </summary>
        protected EPGridView gvUnTransfered;

        /// <summary>
        /// 未移交分页
        /// </summary>
        protected AspNetPager pagerUntransfered;

        /// <summary>
        /// 备注：未生成档号待审档案条目表格
        /// 时间：2012年12月15日 13:03:38
        /// </summary>
        protected EPGridView gvUntransferedWithNoArchiveNum;

        /// <summary>
        /// 未生成档号待审档案条目分页
        /// 时间：2012年12月15日 13:03:43
        /// </summary>
        protected AspNetPager pagerUntransferedWithNoArchiveNum;

        /// <summary>
        /// 是否本单位管理
        /// </summary>
        protected CheckBox chkIsDepartmentReview;

        /// <summary>
        /// 查询控件
        /// </summary>
        protected Web.Views.ArchiveManage.SearchControl searchCtrl;

        protected void pagerTransfered_PageSizeChanging(object sender, EventArgs e)
        {
            BindDone(searchCtrl.WhereString);
        }

        protected void pagerUntransfered_PageSizeChanging(object sender, EventArgs e)
        {
            BindAgent(searchCtrl.WhereString);
        }

        protected void BindAgent()
        {
            BindAgent(string.Empty);
        }

        protected void BindDone()
        {
            BindDone(string.Empty);
        }

        protected void InitialData()
        {
            InitialData(string.Empty);
        }

        /// <summary>
        /// 绑定代办数据
        /// </summary>
        protected void BindAgent(string filter)
        {
            int sum = 0;
            DataTable oDataTable = null;
            WorkFlow oWorkFlow = new WorkFlow();
            int pageSize = this.pagerUntransfered.PageSize;
            User currentUser = (User)Session["CurrentUser"];
            if (currentUser == null)
            {
                throw new Exception("获取当前登陆用户失败");
            }
            oWorkFlow.AutoSignData(CurrentArchiveKind, new Guid(currentUser.User_ID));
            WorkFlowManager wkFlowMgr = new WorkFlowManager();
            int toStatusId = wkFlowMgr.GetStatusIdByTableIdAndStatusName((int)CurrentArchiveKind, CurrentStatusName);
            int JG_toStatusId = wkFlowMgr.GetStatusIdByTableIdAndStatusName((int)CurrentArchiveKind, string.Concat("机关-", CurrentStatusName));
            int JC_toStatusId = wkFlowMgr.GetStatusIdByTableIdAndStatusName((int)CurrentArchiveKind, string.Concat("基层-", CurrentStatusName));
            List<string> statudIdList = new List<string>();
            statudIdList.Add(string.Format("'{0}'", toStatusId));
            statudIdList.Add(string.Format("'{0}'", JG_toStatusId));
            statudIdList.Add(string.Format("'{0}'", JC_toStatusId));
            string f = string.IsNullOrEmpty(filter) ? string.Empty : string.Concat(filter, "  and ");
            if (PassFlowName == "办结")
            {
                ///已生成档号
                oDataTable = oWorkFlow.GetAgent(CurrentArchiveKind, currentUser.User_ID,
                    (this.pagerUntransfered.CurrentPageIndex - 1) * pageSize
                    , pageSize, string.Format(" {1}   archivenum is not null and tostatusid  in ({0})  ", string.Join(",", statudIdList.ToArray()), f), ref sum, FilterSortEnum.OrderByOperateTimeDESC);

                this.gvUnTransfered.DataSource = oDataTable;
                this.gvUnTransfered.DataBind();
                this.pagerUntransfered.RecordCount = sum;

                ///未生成档号
                pageSize = this.pagerUntransferedWithNoArchiveNum.PageSize;
                oDataTable = oWorkFlow.GetAgent(CurrentArchiveKind, currentUser.User_ID,
                    (this.pagerUntransferedWithNoArchiveNum.CurrentPageIndex - 1) * pageSize
                    , pageSize, string.Format("  {1}   archivenum is null and tostatusid  in ({0})  ", string.Join(",", statudIdList.ToArray()), f), ref sum, FilterSortEnum.OrderByOperateTimeDESC);

                DataTable archiveTable = null;
                List<string> myIdList = (from DataRow row in oDataTable.Rows select row["dataid"].ToString()).ToList<string>();
                switch (BaseArchiveType)
                {
                    //文书类
                    case (ArchiveBaseType.Document):
                        IDocumentArchiveService documentArchiveService = UContainer.Resolve<IDocumentArchiveService>();
                        archiveTable = documentArchiveService.GetDocumentArchiveDataByIds(myIdList);
                        break;
                    //会计类
                    case (ArchiveBaseType.Account):
                        IAccountArchiveService accountArchiveService = UContainer.Resolve<IAccountArchiveService>();
                        archiveTable = accountArchiveService.GetAccountArchiveDataByIds(myIdList);
                        break;
                    //基建类
                    case (ArchiveBaseType.BulidProject):
                        IBuildProjectArchiveService buildProjectService = UContainer.Resolve<IBuildProjectArchiveService>();
                        archiveTable = buildProjectService.GetBuildProjectArchiveDataByIds(myIdList);
                        break;
                    //设备类
                    case (ArchiveBaseType.Equipment):
                        IEquipmentService equipService = UContainer.Resolve<IEquipmentService>();
                        archiveTable = equipService.GetEquipmentArchiveDataByIds(myIdList);
                        break;
                    //油气勘探类
                    case (ArchiveBaseType.OliSearch):
                        IOilSearchArchiveService oliSearchService = UContainer.Resolve<IOilSearchArchiveService>();
                        archiveTable = oliSearchService.GetOilSearchArchiveDataByIds(myIdList);
                        break;
                    //音像类
                    case (ArchiveBaseType.AudioVedio):
                        IAudioArchiveService audioService = UContainer.Resolve<IAudioArchiveService>();
                        archiveTable = audioService.GetAudioArchiveDataByIds(myIdList);
                        break;
                    //实物类
                    case (ArchiveBaseType.RealKind):
                        IRealKindArchiveService realService = UContainer.Resolve<IRealKindArchiveService>();
                        archiveTable = realService.GetRealKindArchiveDataByIds(myIdList);
                        break;
                    //科研类
                    case (ArchiveBaseType.Technology):
                        ITechArchiveService techService = UContainer.Resolve<ITechArchiveService>();
                        archiveTable = techService.GetTechArchiveDataByIds(myIdList);
                        break;
                    //光盘类
                    case (ArchiveBaseType.CDKind):
                        ICDArchiveService cdService = UContainer.Resolve<ICDArchiveService>();
                        archiveTable = cdService.GetCDArchiveDataByIds(myIdList);
                        break;
                }

                this.gvUntransferedWithNoArchiveNum.DataSource = archiveTable;
                this.gvUntransferedWithNoArchiveNum.DataBind();
                this.pagerUntransferedWithNoArchiveNum.RecordCount = sum;
            }
            else
            {
                oDataTable = oWorkFlow.GetAgent(CurrentArchiveKind, currentUser.User_ID,
                    (this.pagerUntransfered.CurrentPageIndex - 1) * pageSize
                    , pageSize, string.Format("  {1}  tostatusid  in ({0})  ", string.Join(",", statudIdList.ToArray()), f), ref sum, FilterSortEnum.OrderByOperateTimeDESC);
                this.gvUnTransfered.DataSource = oDataTable;
                this.gvUnTransfered.DataBind();
                this.pagerUntransfered.RecordCount = sum;
            }
            WriteUserLog(string.Format("用户{0}查看了待{1}条目", currentUser.Real_Name, PassFlowName), OracleLogType.ArchiveManage);
        }

        /// <summary>
        /// 绑定已办数据
        /// </summary>
        protected void BindDone(string filter)
        {
            int sum = 0;
            DataTable oDataTable = null;
            WorkFlow oWorkFlow = new WorkFlow();
            int pageSize = this.pagerTransfered.PageSize;
            Web.SystemLogin.Models.User currentUser = (Web.SystemLogin.Models.User)Session["CurrentUser"];
            if (currentUser == null)
            {
                throw new Exception("获取当前登陆用户失败");
            }
            //oDataTable = oWorkFlow.GetDone(CurrentArchiveKind, currentUser.User_ID,
            //    (this.pagerTransfered.CurrentPageIndex - 1) * pageSize
            //    , pageSize, string.Empty, ref sum);

            //时间：2013年3月14日 21:21:49
            //备注：支持一人多岗，提交给自己
            WorkFlowManager wkFlowMgr = new WorkFlowManager();
            int toStatusId = wkFlowMgr.GetStatusIdByTableIdAndStatusName((int)CurrentArchiveKind, CurrentStatusName);
            int JG_toStatusId = wkFlowMgr.GetStatusIdByTableIdAndStatusName((int)CurrentArchiveKind, string.Concat("机关-", CurrentStatusName));
            int JC_toStatusId = wkFlowMgr.GetStatusIdByTableIdAndStatusName((int)CurrentArchiveKind, string.Concat("基层-", CurrentStatusName));
            WorkFlowMessageStatusRuleListCache ruleCache = new ArchiveCacheFacade().GetStatusRuleCache();
            List<WorkFlowMessageStatusRule> statusRuleList = ruleCache.GetRuleByStatusID(toStatusId);
            statusRuleList.AddRange(ruleCache.GetRuleByStatusID(JG_toStatusId));
            string f = string.IsNullOrEmpty(filter) ? string.Empty : string.Concat(filter, "  and ");
            oDataTable = oWorkFlow.GetDone(CurrentArchiveKind, currentUser.User_ID,
                (this.pagerTransfered.CurrentPageIndex - 1) * pageSize
                , pageSize, string.Format("  {1}   fromstatusid in ({0})", string.Join(",", new string[] { toStatusId.ToString(), JG_toStatusId.ToString(), JC_toStatusId.ToString() }), f), ref sum, FilterSortEnum.OrderByOperateTimeDESC);


            this.gvTransfered.DataSource = oDataTable;
            this.gvTransfered.DataBind();
            this.pagerTransfered.RecordCount = sum;

            WriteUserLog(string.Format("用户{0}查看了已{1}条目", currentUser.Real_Name, PassFlowName), OracleLogType.ArchiveManage);
        }

        /// <summary>
        /// 加载代办和已办数据
        /// </summary>
        protected void InitialData(string filter)
        {
            BindAgent(filter);
            BindDone(filter);
        }

        /// <summary>
        /// 代办数据绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvUnTransfered_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRow row = ((DataRowView)e.Row.DataItem).Row;
                string elecFileCount = ArchiveBusiHelper.Instance.GetTechnologyFileCount((int)BaseArchiveType, row["dataid"].ToString());
                if (!string.IsNullOrEmpty(elecFileCount))
                {
                    e.Row.Cells[1].Text = string.Format("<img src='{0}' alt='{1}个电子文件' />",
                        "../../Images/qbz.jpg", elecFileCount);
                }
                else
                {
                    e.Row.Cells[1].Text = string.Empty;
                }
                e.Row.Cells[4].Text = IUserService.GetUserNameById(row["CREATEUSERID"].ToString());
                e.Row.Cells[5].Text = string.Format("<a target='_blank' href='ArchiveFlowEdit.aspx?archiveId={0}&archivetype={1}&currentstatusname={2}' >{3}</a>",
                    row["DATAID"], (int)CurrentArchiveKind, CurrentStatusName, row["TITLE"]);
                e.Row.Cells[8].Text = ICodeTableService.GetpkNameByCodepkValue(row["F_SECURITYTYPE"].ToString());
            }
        }

        /// <summary>
        /// 代办-已生成档号分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void pagerUntransfered_PageChanging(object sender, PageChangingEventArgs e)
        {
            pagerUntransfered.CurrentPageIndex = e.NewPageIndex;
            BindAgent(searchCtrl.WhereString);
        }

        /// <summary>
        /// 代办-未生成档号分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void pagerUntransferedWithNoArchiveNum_PageChanging(object sender, PageChangingEventArgs e)
        {
            pagerUntransferedWithNoArchiveNum.CurrentPageIndex = e.NewPageIndex;
            BindAgent();
        }

        /// <summary>
        /// 代办编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvUnTransfered_RowEditing(object sender, GridViewEditEventArgs e)
        {
            /*
             *时间：2012年12月18日 23:36:48
             *备注：currentstatusname 参数用于标注当前流程所处的节点，用于退回按钮退回到对应的处理页面
             */
            string pkValue = this.gvUnTransfered.DataKeys[e.NewEditIndex].Value.ToString();
            if (PassFlowName == "移交")
            {
                this.Response.Redirect("../ArchiveManage/ArchiveEdit.aspx?op=edit&archiveId=" + pkValue + "&archivetype=" + (int)CurrentArchiveKind);
            }
            else
            {
                this.Response.Redirect("../ArchiveFlowView/ArchiveFlowEdit.aspx?op=edit&archiveId=" + pkValue + "&archivetype=" + (int)CurrentArchiveKind + "&currentstatusname=" + CurrentStatusName);
            }

        }

        /// <summary>
        /// 代办编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvUntransferedWithNoArchiveNum_RowEditing(object sender, GridViewEditEventArgs e)
        {
            /*
             *时间：2012年12月18日 23:36:48
             *备注：currentstatusname 参数用于标注当前流程所处的节点，用于退回按钮退回到对应的处理页面
             */
            string pkValue = this.gvUntransferedWithNoArchiveNum.DataKeys[e.NewEditIndex].Value.ToString();
            if (PassFlowName == "移交")
            {
                this.Response.Redirect("../ArchiveManage/ArchiveEdit.aspx?op=edit&archiveId=" + pkValue + "&archivetype=" + (int)CurrentArchiveKind);
            }
            else
            {
                this.Response.Redirect("../ArchiveFlowView/ArchiveFlowEdit.aspx?op=edit&archiveId=" + pkValue + "&archivetype=" + (int)CurrentArchiveKind + "&currentstatusname=" + CurrentStatusName);
            }

        }

        /// <summary>
        /// 代办删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvUnTransfered_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                bool bReturn = false;
                string pkValue = this.gvUnTransfered.DataKeys[e.RowIndex].Value.ToString();
                switch (CurrentArchiveKind)
                {
                    case ArchiveTableEnum.Account:
                        IAccountArchiveService account = UContainer.Resolve<IAccountArchiveService>();
                        bReturn = account.DeleteData(pkValue);
                        break;
                    case ArchiveTableEnum.AudioVedio:
                        IAudioArchiveService audio = UContainer.Resolve<IAudioArchiveService>();
                        bReturn = audio.DeleteData(pkValue);
                        break;
                    case ArchiveTableEnum.BulidProject:
                        IBuildProjectArchiveService build = UContainer.Resolve<IBuildProjectArchiveService>();
                        bReturn = build.DeleteData(pkValue);
                        break;
                    case ArchiveTableEnum.CDKind:
                        ICDArchiveService cd = UContainer.Resolve<ICDArchiveService>();
                        bReturn = cd.DeleteData(pkValue);
                        break;
                    case ArchiveTableEnum.Document:
                        IDocumentArchiveService document = UContainer.Resolve<IDocumentArchiveService>();
                        bReturn = document.DeleteData(pkValue);
                        break;
                    case ArchiveTableEnum.Equipment:
                        IEquipmentService equipment = UContainer.Resolve<IEquipmentService>();
                        equipment.DeleteData(pkValue);
                        break;
                    case ArchiveTableEnum.OliSearch:
                        IOilSearchArchiveService oil = UContainer.Resolve<IOilSearchArchiveService>();
                        oil.DeleteData(pkValue);
                        break;
                    case ArchiveTableEnum.RealKind:
                        IRealKindArchiveService realKind = UContainer.Resolve<IRealKindArchiveService>();
                        realKind.DeleteData(pkValue);
                        break;
                    case ArchiveTableEnum.Technology:
                        ITechArchiveService tech = UContainer.Resolve<ITechArchiveService>();
                        tech.DeleteData(pkValue);
                        break;
                }

                if (bReturn)
                {
                    Alert("删除成功！");
                    WriteUserLog(string.Format("用户{0}成功删除ID为{1}的{2}类档案", CurrentUser.Real_Name, pkValue, CurrentArchiveKind), OracleLogType.ArchiveManage);
                    BindAgent();
                }
            }
            catch (Exception ex)
            {
                Alert("操作出现异常，请重新再试！");
                WriteErrorLog(ex.Message, OracleLogType.ArchiveManage);
            }
        }

        /// <summary>
        /// 已办绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvTransfered_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRow row = ((DataRowView)e.Row.DataItem).Row;
                string elecFileCount = ArchiveBusiHelper.Instance.GetTechnologyFileCount((int)BaseArchiveType, row["dataid"].ToString());
                if (!string.IsNullOrEmpty(elecFileCount))
                {
                    e.Row.Cells[1].Text = string.Format("<img src='{0}' alt='{1}个电子文件' />",
                        "../../Images/qbz.jpg", elecFileCount);
                }
                else
                {
                    e.Row.Cells[1].Text = string.Empty;
                }
                e.Row.Cells[3].Text = IUserService.GetUserNameById(row["CREATEUSERID"].ToString());
                e.Row.Cells[7].Text = ICodeTableService.GetpkNameByCodepkValue(row["F_SECURITYTYPE"].ToString());
                e.Row.Cells[4].Text = string.Format("<a target='_blank' href='../ArchiveView/ArchivePreview.aspx?op=scan&archiveId={0}&archivetype={1}' >{2}</a>",
                    row["DATAID"], (int)CurrentArchiveKind, row["TITLE"]);
            }
        }

        /// <summary>
        /// 已办分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void pagerTransfered_PageChanging(object sender, PageChangingEventArgs e)
        {
            pagerTransfered.CurrentPageIndex = e.NewPageIndex;
            BindDone(searchCtrl.WhereString);
        }

        /// <summary>
        /// 移交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnTransfer_Click(object sender, EventArgs e)
        {
            ArrayList keys = this.gvUnTransfered.SelectItems;
            if (keys.Count == 0)
            {
                Alert("请先选择待" + PassFlowName + "的条目！");
                return;
            }
            DataTable dt = this.gvUnTransfered.DataSource as DataTable;
            foreach (string key in keys)
            {
                Guid recordId = new Guid(key);
                Guid currentUserId = new Guid(this.CurrentUser.User_ID);

                //用户查看详细信息时传值给 SignData 方法
                int statusId = Convert.ToInt32(dt.Select("DataID='" + key + "'")[0]["StatusID"]);

                //TODO 移交
                WorkFlowModel oWorkFlowModel = new WorkFlowModel();

                ///时间：2012年12月31日 16:02:05
                ///备注：兼容2套流程
                int originaleStatusID;
                string operateName = PassFlowName;
                if (this.CurrentUser.Org_FullFondsNum == CommonUtil.GetConfigValue("ArchiveManage", "InstitutionFullFondsNum"))
                {
                    //机关流程
                    originaleStatusID = new WorkFlowManager().GetStatusIdByTableIdAndStatusName((int)CurrentArchiveKind, string.Concat("机关-", CurrentStatusName));
                    operateName = string.Concat("机关-", operateName);
                }
                else
                {
                    //本单位流程
                    if (chkIsDepartmentReview.Checked)
                    {
                        originaleStatusID = new WorkFlowManager().GetStatusIdByTableIdAndStatusName((int)CurrentArchiveKind, string.Concat("基层-", CurrentStatusName));
                        operateName = string.Concat("基层-", operateName);
                    }
                    //完整流程
                    else
                    {
                        originaleStatusID = new WorkFlowManager().GetStatusIdByTableIdAndStatusName((int)CurrentArchiveKind, CurrentStatusName);
                    }
                }

                oWorkFlowModel.FromStatusID = originaleStatusID;//当前数据的状态
                oWorkFlowModel.FromUserID = currentUserId;//当前用户的 userId ，从session取
                oWorkFlowModel.TableID = (int)CurrentArchiveKind;
                oWorkFlowModel.RecordID = recordId;
                oWorkFlowModel.OperateLogID = Guid.NewGuid();
                //oWorkFlowModel.CommentMessage = "上报时候不需要，审核时候带审核意见";

                WorkFlowMessageStatusRuleListCache ruleCache = new ArchiveCacheFacade().GetStatusRuleCache();
                List<WorkFlowMessageStatusRule> listRule = ruleCache.GetRuleByStatusID(oWorkFlowModel.FromStatusID);

                WorkFlowMessageStatusRule rule = ruleCache.GetRuleByStatusIDAndOperateName(oWorkFlowModel.FromStatusID, operateName);
                oWorkFlowModel.OperateID = rule.OperateID;//取驱动的ID
                WorkFlow oWorkFlow = new WorkFlow();
                oWorkFlow.SignData(oWorkFlowModel);//

                if (this.CurrentUser.Org_FullFondsNum == CommonUtil.GetConfigValue("ArchiveManage", "InstitutionFullFondsNum"))
                {
                    oWorkFlow.FlowProcess(oWorkFlowModel);//有操作，就用。涉及流程
                }
                else
                {
                    //add on 2013年3月9日 
                    //移交操作只提交给本部门的处理人
                    //rule.ToRoleID 处理人角色id 
                    oWorkFlow.FlowProcess(oWorkFlowModel, IUserService.GetUserDtByQZHAndToRoleID(currentUserId, rule.ToRoleID.ToString()));
                }

                //oWorkFlow.FlowProcess(oWorkFlowModel);//有操作，就用。涉及流程
                //oWorkFlow.FlowStart(oWorkFlowModel);//数据临时保存时候，用。不涉及流程
                WriteUserLog(string.Format("用户{0}{1}ID为{2}的档案", CurrentUser.Real_Name, PassFlowName, key), OracleLogType.ArchiveManage);
            }
            InitialData();
            Alert("档案已" + PassFlowName + "！");
            return;
        }

        /// <summary>
        /// 审核通过
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnVerify_Click(object sender, EventArgs e)
        {
            //
            ArrayList keys = this.gvUnTransfered.SelectItems;
            if (keys.Count == 0)
            {
                Alert("请先选择待" + PassFlowName + "的条目！");
                return;
            }
            DataTable dt = this.gvUnTransfered.DataSource as DataTable;
            foreach (string key in keys)
            {
                Guid recordId = new Guid(key);
                Guid currentUserId = new Guid(this.CurrentUser.User_ID);

                //用户查看详细信息时传值给 SignData 方法
                int statusId = Convert.ToInt32(dt.Select("DataID='" + key + "'")[0]["StatusID"]);


                object objFullFondsNum = dt.Select("DataID='" + key + "'")[0]["FULLFONDSNUM"];
                string fullFondsNum = objFullFondsNum == null || objFullFondsNum == DBNull.Value ? "" : objFullFondsNum.ToString();
                string operateName = PassFlowName;
                if (chkIsDepartmentReview != null && chkIsDepartmentReview.Checked)
                {
                    operateName = string.Concat("基层-", operateName);
                }
                else if (chkIsDepartmentReview == null)
                {
                    if (fullFondsNum == CommonUtil.GetConfigValue("ArchiveManage", "InstitutionFullFondsNum"))
                    {
                        operateName = string.Concat("机关-", operateName);
                    }
                }

                try
                {
                    //TODO 审核通过
                    WorkFlowModel oWorkFlowModel = new WorkFlowModel();
                    oWorkFlowModel.FromStatusID = statusId;//当前数据的状态
                    oWorkFlowModel.FromUserID = currentUserId;//当前用户的 userId ，从session取
                    oWorkFlowModel.TableID = (int)CurrentArchiveKind;
                    oWorkFlowModel.RecordID = recordId;
                    oWorkFlowModel.OperateLogID = Guid.NewGuid();
                    //oWorkFlowModel.CommentMessage = "上报时候不需要，审核时候带审核意见";

                    WorkFlowMessageStatusRuleListCache ruleCache = new ArchiveCacheFacade().GetStatusRuleCache();
                    WorkFlowMessageStatusRule rule = ruleCache.GetRuleByStatusIDAndOperateName(oWorkFlowModel.FromStatusID, operateName);
                    oWorkFlowModel.OperateID = rule.OperateID;//取驱动的ID
                    WorkFlow oWorkFlow = new WorkFlow();
                    oWorkFlow.SignData(oWorkFlowModel);//
                    //bool canEdit = false;
                    //bool canView = false;
                    //bool canOperate = false;
                    //oWorkFlow.GetPrivilege(CurrentArchiveKind, this.CurrentUser.User_ID, key, ref canEdit, ref canView, ref canOperate);
                    //oWorkFlow.SignData(oWorkFlowModel);
                    ///接收给自己
                    if (PassFlowName == "接收")
                    {
                        oWorkFlow.FlowProcess(oWorkFlowModel, currentUserId);
                    }
                    else
                    {
                        oWorkFlow.FlowProcess(oWorkFlowModel);//有操作，就用。涉及流程
                    }
                    //获取表名
                    string tableName = new ArchiveCacheFacade().GetStausCache().GetTableName((int)CurrentArchiveKind);
                    ArchiveCommon ac = UContainer.Resolve<ArchiveCommon>();


                    //办结时候，更新全宗号
                    var listOperate = new List<string>();
                    listOperate.Add("基层-办结");
                    listOperate.Add("办结");
                    if (listOperate.Contains(operateName.Trim()))
                        ac.UpdateFullFondsNum(this.CurrentUser.Org_FullFondsNum, tableName, key);

                    //提交日志
                    //oWorkFlow.FlowStart(oWorkFlowModel);//数据临时保存时候，用。不涉及流程
                    WriteUserLog(string.Format("用户{0}{1}ID为{2}的档案", CurrentUser.Real_Name, PassFlowName, key), OracleLogType.ArchiveManage);
                    InitialData();
                    Alert("档案已" + PassFlowName + "！");
                }
                catch (Exception ex)
                {
                    Alert("办结过程发生错误,已经回滚。错误消息:" + ex.Message);
                }
            }
        }

        /// <summary>
        /// 退回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBack_Click(object sender, EventArgs e)
        {
            //bool hasCheckData = true;
            ////
            //ArrayList keys = this.gvUnTransfered.SelectItems;
            //if (keys.Count == 0)
            //{
            //    keys = this.gvUntransferedWithNoArchiveNum.SelectItems;
            //    if (keys.Count == 0)
            //    {
            //        hasCheckData = false;
            //    }
            //}
            ArrayList keys = new ArrayList();
            DataTable dt = null;
            if (PassFlowName.Equals("办结")) //档案整理-未生成档号 退回
            {
                keys = this.gvUntransferedWithNoArchiveNum.SelectItems;
                //未生成档号
                dt = this.gvUntransferedWithNoArchiveNum.DataSource as DataTable;

            }
            else //其他退回
            {
                keys = this.gvUnTransfered.SelectItems;
                dt = this.gvUnTransfered.DataSource as DataTable;
            }
            if (keys.Count == 0)
            {
                Alert("请先选择待" + BackFlowName + "的条目！");
                return;
            }


            //已生成档号
            //dt = this.gvUnTransfered.DataSource as DataTable;
            //keys = this.gvUnTransfered.SelectItems;
            //ExecuteFlow(keys, dt);


            //ExecuteFlow(keys, dt);
            Guid createUserId = new Guid();

            foreach (string key in keys)
            {
                Guid recordId = new Guid(key);
                Guid currentUserId = new Guid(this.CurrentUser.User_ID);

                //用户查看详细信息时传值给 SignData 方法
                int statusId = Convert.ToInt32(dt.Select("DataID='" + key + "'")[0]["StatusID"]);
                createUserId = new Guid(dt.Select("DataID='" + key + "'")[0]["CREATEUSERID"].ToString());


                object objFullFondsNum = dt.Select("DataID='" + key + "'")[0]["FULLFONDSNUM"];
                string fullFondsNum = objFullFondsNum == null || objFullFondsNum == DBNull.Value ? "" : objFullFondsNum.ToString();
                string operateName = BackFlowName;
                if (chkIsDepartmentReview != null && chkIsDepartmentReview.Checked)
                {
                    operateName = string.Concat("基层-", operateName);
                }
                else if (chkIsDepartmentReview == null)
                {
                    if (fullFondsNum == CommonUtil.GetConfigValue("ArchiveManage", "InstitutionFullFondsNum"))
                    {
                        operateName = string.Concat("机关-", operateName);
                    }
                }

                //TODO 审核通过
                WorkFlowModel oWorkFlowModel = new WorkFlowModel();
                oWorkFlowModel.FromStatusID = statusId;//当前数据的状态
                oWorkFlowModel.FromUserID = currentUserId;//当前用户的 userId ，从session取
                oWorkFlowModel.TableID = (int)CurrentArchiveKind;
                oWorkFlowModel.RecordID = recordId;
                oWorkFlowModel.OperateLogID = Guid.NewGuid();
                //oWorkFlowModel.CommentMessage = "上报时候不需要，审核时候带审核意见";

                WorkFlowMessageStatusRuleListCache ruleCache = new ArchiveCacheFacade().GetStatusRuleCache();
                WorkFlowMessageStatusRule rule = ruleCache.GetRuleByStatusIDAndOperateName(oWorkFlowModel.FromStatusID, operateName);
                oWorkFlowModel.OperateID = rule.OperateID;//取驱动的ID
                WorkFlow oWorkFlow = new WorkFlow();
                oWorkFlow.SignData(oWorkFlowModel);
                oWorkFlow.FlowProcess(oWorkFlowModel, createUserId);//有操作，就用。涉及流程
                //oWorkFlow.FlowStart(oWorkFlowModel);//数据临时保存时候，用。不涉及流程
                WriteUserLog(string.Format("用户{0}{1}ID为{2}的档案", CurrentUser.Real_Name, BackFlowName, key), OracleLogType.ArchiveManage);
            }

            InitialData();
            Alert("档案已" + BackFlowName + "！");
            return;
        }

        private void ExecuteFlow(ArrayList keys, DataTable dt)
        {
            foreach (string key in keys)
            {
                Guid recordId = new Guid(key);
                Guid currentUserId = new Guid(this.CurrentUser.User_ID);

                //用户查看详细信息时传值给 SignData 方法
                int statusId = Convert.ToInt32(dt.Select("DataID='" + key + "'")[0]["StatusID"]);

                object objFullFondsNum = dt.Select("DataID='" + key + "'")[0]["FULLFONDSNUM"];
                string fullFondsNum = objFullFondsNum == null || objFullFondsNum == DBNull.Value ? "" : objFullFondsNum.ToString();
                string operateName = BackFlowName;
                if (fullFondsNum == CommonUtil.GetConfigValue("ArchiveManage", "InstitutionFullFondsNum"))
                {
                    operateName = string.Concat("机关-", operateName);
                }

                //TODO 审核通过
                WorkFlowModel oWorkFlowModel = new WorkFlowModel();
                oWorkFlowModel.FromStatusID = statusId;//当前数据的状态
                oWorkFlowModel.FromUserID = currentUserId;//当前用户的 userId ，从session取
                oWorkFlowModel.TableID = (int)CurrentArchiveKind;
                oWorkFlowModel.RecordID = recordId;
                oWorkFlowModel.OperateLogID = Guid.NewGuid();
                //oWorkFlowModel.CommentMessage = "上报时候不需要，审核时候带审核意见";

                WorkFlowMessageStatusRuleListCache ruleCache = new ArchiveCacheFacade().GetStatusRuleCache();
                WorkFlowMessageStatusRule rule = ruleCache.GetRuleByStatusIDAndOperateName(oWorkFlowModel.FromStatusID, operateName);
                oWorkFlowModel.OperateID = rule.OperateID;//取驱动的ID
                WorkFlow oWorkFlow = new WorkFlow();
                oWorkFlow.SignData(oWorkFlowModel);
                oWorkFlow.FlowProcess(oWorkFlowModel);//有操作，就用。涉及流程
                //oWorkFlow.FlowStart(oWorkFlowModel);//数据临时保存时候，用。不涉及流程

            }
        }

    }
}